package com.xinzhi.service.impl;

import com.xinzhi.log.LoginLog;
import com.xinzhi.mapper.LoginMapper;
import com.xinzhi.mapper.PhoAndPwdLoginMapper;
import com.xinzhi.pojo.User;
import com.xinzhi.pojo.dto.LoginRequest;
import com.xinzhi.service.IPhoAndPwdLoginService;
import com.xinzhi.utils.RedisUtils;
import com.xinzhi.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.concurrent.*;

@Service
public class PhoAndPwdLoginServiceImpl implements IPhoAndPwdLoginService {
    @Autowired
    private PhoAndPwdLoginMapper userzeroMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private LoginLog loginLog;
    /**
     * 根据手机号和密码登录
     * @param loginRequest 登录请求参数
     * @return
     */
    @Override
    public Result LoginByPwdAndPho(LoginRequest loginRequest) {
        if (loginRequest.getPassword() == null || loginRequest.getPhone()== null)
            return Result.error("请输入手机号或密码");
        if (!isValidPhoneNumber(loginRequest.getPhone()))
            return Result.error("手机号格式错误,请重新输入");
        if (!isValidPassword(loginRequest.getPassword()))
            return Result.error("密码格式错误,请重新输入");
        User o = (User) redisUtils.get("user"+loginRequest.getPhone());
        if (o!=null) {
            String passwordHash = DigestUtils.md5DigestAsHex(loginRequest.getPassword().getBytes());
            if (passwordHash.equals(o.getPassword())) {
                //异步日志
                loginLog.insertLoginLog(o.getId(),1);
                return Result.ok(o);
            }
        }
       User user = userzeroMapper.phoAndPwdLogin(loginRequest);
        if (user ==null)
            return Result.error("手机号还未注册，请注册");
        String passwordHash = DigestUtils.md5DigestAsHex(loginRequest.getPassword().getBytes());
        if (!passwordHash.equals(user.getPassword()))
            return Result.error("密码错误，请重新输入");
        redisUtils.set("user"+loginRequest.getPhone(),user,300);
        //异步日志
        loginLog.insertLoginLog(user.getId(),1);
        return Result.ok(user);
    }
    /**
     * 判断手机号格式是否正确
     * @param phone 手机号
     * @return
     */
    @Override
    public boolean isValidPhoneNumber(String phone) {
        return phone.matches("^1[3456789]\\d{9}$");
    }

    /**
     * 判断密码格式是否正确
     * @param password 密码
     * @return
     */
    @Override
    public boolean isValidPassword(String password) {
        return password.matches("^[a-zA-Z0-9]{8,30}$");
    }

    /**
     * 判断手机号是否已注册
     * @param phone 手机号
     * @return
     */
    @Override
    public boolean isPhoneUnique(LoginRequest phone) {
        User user= userzeroMapper.phoAndPwdLogin(phone);
        return user == null ? false : true;
    }
}
